package cn.lsg.util;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.net.URLCodec;

/**
 * @author Administrator
 * 
 */
public class UtilEncrypt {

	/**
	 * MD5 encode
	 * 
	 * @param str
	 * @return
	 */
	public static final String MD5Encode(String str) {
		return new String(DigestUtils.md5Hex(str)).toUpperCase();
	}

	/**
	 * URL encode
	 * 
	 * @param url
	 * @return
	 */
	public static final String URLEncode(String url) {
		URLCodec code = new URLCodec();
		try {
			return code.encode(url);
		} catch (EncoderException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * URL decode
	 * 
	 * @param str
	 * @return {@link String}
	 * */
	public static final String URLDecode(String str) {
		URLCodec codec = new URLCodec();
		try {
			return codec.decode(str);
		} catch (DecoderException e) {
			return null;
		}
	}

	/**
	 * URI encode
	 * **/
	public static String URIEncode(String str)
			throws UnsupportedEncodingException {
		if (str.indexOf("%") != -1) {
			return str;
		}

		String isoStr = new String(str.getBytes("UTF8"), "ISO-8859-1");
		char[] chars = isoStr.toCharArray();

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < chars.length; i++) {

			if ((chars[i] <= 'z' && chars[i] >= 'a')
					|| (chars[i] <= 'Z' && chars[i] >= 'A') || chars[i] == '-'
					|| chars[i] == '_' || chars[i] == '.' || chars[i] == '!'
					|| chars[i] == '~' || chars[i] == '*' || chars[i] == '\''
					|| chars[i] == '(' || chars[i] == ')' || chars[i] == ';'
					|| chars[i] == '/' || chars[i] == '?' || chars[i] == ':'
					|| chars[i] == '@' || chars[i] == '&' || chars[i] == '='
					|| chars[i] == '+' || chars[i] == '$' || chars[i] == ','
					|| chars[i] == '#'
					|| (chars[i] - '0' >= 0 && chars[i] - '0' <= 9)) {
				sb.append(chars[i]);
			} else {

				sb.append("%");
				sb.append(Integer.toHexString(chars[i]));

			}
		}
		return sb.toString();
	}

}
